﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using ImTag.Mongo;

namespace ImTag.Silverlight.Web
{
    /// <summary>
    /// Summary description for ImTagService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class ImTagService : System.Web.Services.WebService
    {


        [WebMethod]
        public List<Image> LoadImages()
        {
            var files = System.IO.Directory.GetFiles(Server.MapPath("Images")).Select(s => "Images/" + System.IO.Path.GetFileName(s)).ToArray();
            var imagesInDB = MongoManager.LoadAllFiles();

            imagesInDB = imagesInDB.Where(im => files.Contains(im.ImagePath)).ToList();

            foreach (var path in files)
                if (!imagesInDB.Select(i => i.ImagePath).Contains(path))
                    imagesInDB.Add(new Image() { ImagePath = path });


            return imagesInDB;
        }
        [WebMethod]
        public List<string> LoadTags()
        {
            return MongoManager.LoadAllTags();
        }


        [WebMethod]
        public List<Image> LoadTaglessImages()
        {
            var files = System.IO.Directory.GetFiles(Server.MapPath("Images")).Select(s => "Images/" + System.IO.Path.GetFileName(s)).ToArray();
            var imagesInDB = MongoManager.LoadAllFiles();

            return files.Where(path => !imagesInDB.Select(i => i.ImagePath).Contains(path)).Select(path => new Image() { ImagePath = path }).ToList();
        }


        [WebMethod]
        public List<Image> SearchImages(List<string> tags)
        {
            var realTags = tags.Where(s => s != null && s != "");
            if (realTags.Count() != 0)
                return MongoManager.SearchImages(realTags);
            else
                return LoadImages();
        }


        [WebMethod]
        public bool AddTag(string tag, string filename)
        {
            return MongoManager.AddTag(tag, filename);
        }
    }

   
}
